package com.sneaker.shower.controller;

import com.sneaker.shower.common.BaseView;
import com.sneaker.shower.service.FileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.activation.MimetypesFileTypeMap;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Controller
@Api("文件API")
public class FileController {

    private final FileService fileService;

    private MimetypesFileTypeMap mimetypesFileTypeMap = new MimetypesFileTypeMap();

    @Autowired
    public FileController(FileService fileService) {
        this.fileService = fileService;
    }

    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/file/upload")
    @ApiOperation("文件上传")
    public BaseView<String> upload(@RequestParam("file") MultipartFile file) {
        return new BaseView<>(fileService.upload(file));
    }

    @RequestMapping(method = RequestMethod.GET, value = "/file/download")
    @ApiOperation("文件下载")
    public void download(String file, HttpServletResponse response) {
        response.reset();
        try {
            String fileName = fileService.download(file, response.getOutputStream());
            response.setContentType(mimetypesFileTypeMap.getContentType(file));
            response.setHeader("Content-Disposition", "inline;filename=" + fileName);
        } catch (IOException e) {
            response.setStatus(404);
        }

    }
}
